import xaoi from './xaoi.js'
import conf from './config.js'

var ajax = xaoi.ajax(function() {
	this.http = uni.request;

	//获取uniapp设备类型
	this.req.headers.uniPlatform = uni.getSystemInfoSync().uniPlatform;

	let token = xaoi.store('token')
	if (token) {
		this.req.headers.Authorization = 'Bearer ' + token;
		this.req.headers.Token = token
	}
	console.log(token, 'tokentokentokentoken')

	let openid = uni.getStorageSync('openid')
	if (openid) {
		this.req.headers.openid = openid;
	}

	if (this.req.url.indexOf('://') === -1) {
		if (this.req.url.indexOf('/') === 0) {
			this.req.url = '__HOST____API__' + this.req.url
		} else {
			this.req.url = '__HOST____API____APP__' + '/' + this.req.url
		}
	}
}, function(res) {
	if (res && res.code == conf.codes.success) {
		return res.data
	} else if (res && res.code && conf.codes.tologin.indexOf(res.code) !== -1) {
		uni.hideLoading()
		uni.showModal({
			title: '温馨提示',
			content: '请先登录~',
			showCancel: false,
			confirmText: '去登录',
			confirmColor: '#0f956e',
			complete() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
		})
	} else if (res && res.message) {
		console.error(res)
		uni.showToast({
			icon: 'error',
			title: res.message || 'error',
		})
	}
	return new Promise(ok => {})
})

//请求默认是post，如果需要其他请求类型可在添加一层处理器
export let post = ajax(function() {
	// this.req.withCredentials = true;
});

export let uploadFile = function(url, file) {
	return new Promise(ok => {

		if (url.indexOf('://') === -1) {
			if (url.indexOf('/') === 0) {
				url = '__HOST____API__' + url
			} else {
				url = '__HOST____API____APP__/' + url
			}
		}

		let user = xaoi.store('user')

		uni.uploadFile({
			url,
			filePath: file,
			name: 'file',
			header: {
				Authorization: 'Bearer ' + user.token
			},
			success: (res) => {
				res = JSON.parse(res.data)

				if (res && res.code == conf.codes.success) {
					ok(res.data)
					return;
				} else if (res && res.code && conf.codes.tologin.indexOf(res.code) !== -1) {
					uni.showModal({
						title: '温馨提示',
						content: '请先登录~',
						showCancel: false,
						confirmText: '去登录',
						confirmColor: '#0f956e',
						complete() {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					})
				} else if (res && res.message) {
					console.error(res)
					uni.showToast({
						icon: 'error',
						title: res.message || 'error',
					})
				}
				return new Promise(ok => {})
			}
		});

	})
}